package network;

import android.content.Intent;

import com.google.gson.Gson;
import com.pires.keyspirit.BaseApplication;
import com.pires.keyspirit.MainActivity;

import java.io.IOException;
import java.lang.reflect.Type;

import bean.LoginUser;
import bean.PreDealResult;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 对后台数据进行预解析
 * 由于后台data接口返回正常和异常的data数据格式不一样,采泛型T传入时,会引起Gson解析出错
 *
 * @author: xiaoluo
 * @date: 2017-03-02 16:50
 */
final class TupaiResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    TupaiResponseConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理,
     * // ret: 1 正常，0 有问题, 2 token失效
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            PreDealResult result = gson.fromJson(response, PreDealResult.class);
            int ret = result.ret;
            if (ret == 1) {
                LoginUser.TokenVerity.setToken(result.token);
                return gson.fromJson(response, type);
            }
            if (ret == 2) {
                LoginUser.TokenVerity.setToken("");

                Intent intent = new Intent(BaseApplication.getAppContext(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseApplication.getAppContext().startActivity(intent);

                throw new APIException(result.info);
            } else {
                throw new APIException(result.info);
            }
        } finally {
            value.close();
        }
    }
}
